package game

import (
	"fmt"
	"github.com/robfig/cron/v3"
	"math"
	"math/rand"
	"server/GoUtil"
	"server/MergeConst"
	"server/db"
	"server/msg"
	"sort"
	"strconv"
	"strings"
	"time"

	"google.golang.org/protobuf/proto"
)

type ChampshipsManager struct {
	MStatus             int32
	MChampshipMap       map[int32]*db.SqlChampshipsStruct
	MChampshipPlayerMap map[int32][]*msg.ChampshipsPlayerInfo
	IsSettle            int32
	IsLoadDB            bool
	MUpdateNotifyList   []int32
	McronSave           *cron.Cron
	McronSaveID         cron.EntryID
	RobotCronID         cron.EntryID
	RobotCronID10s      cron.EntryID
	MPlayerBaseInfoMap  map[int32]*db.ResPlayerBaseInfo
}

func (p *ChampshipsManager) SaveDataFromDB(Key interface{}) bool {

	return true
}

func (p *ChampshipsManager) AIGrow1() {

}

func (p *ChampshipsManager) DeleteOutLineChampship(CurChampshipsId int32) {
	sqlStr := "DELETE FROM t_championships_data WHERE CurChampshipsId = ?"

	for k, v := range p.MChampshipPlayerMap {
		if v[0].CurChampshipsId == CurChampshipsId {
			delete(p.MChampshipPlayerMap, k)
		}
	}
	result, err := db.SqlDb.Exec(sqlStr, CurChampshipsId)
	if err != nil {
		fmt.Printf("exec failed, err:%v\n", err)
		return
	}
	affectedRows, err := result.RowsAffected()
	if err != nil {
		fmt.Printf("get affected failed, err:%v\n", err)
		return
	} else {
		fmt.Printf("delete t_championships_data affectedRows:%d\n", affectedRows)
	}
}

func (p *ChampshipsManager) DeleteUneffectPlayer(deleteIds []int32) {
	sqlStr := "DELETE FROM t_player_baseinfo WHERE dwUin = ?"

	for i := 0; i < len(deleteIds); i++ {
		_, err := db.SqlDb.Exec(sqlStr, deleteIds[i])
		if err != nil {
			fmt.Printf("exec failed, err:%v\n", err)
		}

	}
}

func (p *ChampshipsManager) GetFriendListId(id int32) []int32 {

	sqlStr := "SELECT * FROM t_player_Friend_Data WHERE dwUin = ?"
	sqlStruck := db.SqlFriendStruct{}
	ret := []int32{}

	if err := db.SqlDb.Get(&sqlStruck, sqlStr, id); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)

	} else {
		if sqlStruck.FriendList != "" {
			arr := strings.Split(sqlStruck.FriendList, "_")
			for i := 0; i < len(arr); i++ {
				id, _ := strconv.ParseInt(arr[i], 10, 32)
				ret = append(ret, int32(id))
			}
		}
	}
	return ret
}

func (p *ChampshipsManager) NotifyOpenNewChampShip(args []interface{}) {
	go func() {
		G_GameLogicPtr.M_SvrGlobal.CurChampshipsId = G_GameLogicPtr.M_SvrGlobal.CurChampshipsId + 1
		G_GameLogicPtr.M_SvrGlobal.StartChampshipsSvrTime = args[0].(int32)
	}()
}

func (p *ChampshipsManager) OpenNewChampShip(args []interface{}) {

	G_GameLogicPtr.M_SvrGlobal.CurChampshipsId = G_GameLogicPtr.M_SvrGlobal.CurChampshipsId + 1
	G_GameLogicPtr.M_SvrGlobal.StartChampshipsSvrTime = args[0].(int32)
	p.MUpdateNotifyList = []int32{}

	sqlStr := "SELECT * FROM t_player_baseinfo"
	sqlStrucks := []db.ResPlayerBaseInfo{}
	if err := db.SqlDb.Select(&sqlStrucks, sqlStr); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)
		return
	} else {

	}
	deleteIds := []int32{}
	sqlStrucksList := []db.ResPlayerBaseInfo{}
	for i := 0; i < len(sqlStrucks); i++ {
		if sqlStrucks[i].UserName == "" {
			deleteIds = append(deleteIds, sqlStrucks[i].DwUin)
		} else {
			sqlStrucksList = append(sqlStrucksList, sqlStrucks[i])
		}
	}
	sqlStrucks = sqlStrucksList
	p.DeleteUneffectPlayer(deleteIds)

	sort.Slice(sqlStrucks, func(i, j int) bool {
		if sqlStrucks[i].Level != sqlStrucks[j].Level {
			return sqlStrucks[i].Level < sqlStrucks[j].Level
		} else {
			return sqlStrucks[i].Exp < sqlStrucks[j].Exp
		}

	})
	var playerCnt int = 15
	groups := int(math.Ceil((float64)(len(sqlStrucks)) / float64(playerCnt)))
	StartRobotUin := 200000
	p.MStatus = 1
	rand.Seed(time.Now().Unix())
	for i := 0; i < groups; i++ {
		if i < groups-1 {
			temp := db.SqlChampshipsStruct{}
			temp.CurChampshipsId = G_GameLogicPtr.M_SvrGlobal.CurChampshipsId
			CSPlayerInfo := []*msg.ChampshipsPlayerInfo{}

			strr := []string{}
			for j := 0; j < int(playerCnt); j++ {
				dwUin := sqlStrucks[i*int(playerCnt)+j].DwUin
				res := strconv.Itoa(int(dwUin)) + "_" + "1" + "_" + "0" + "_" + "0" + "_" + "1" + "_" + strconv.Itoa(int(G_GameLogicPtr.M_SvrGlobal.CurChampshipsId)) + "_0"
				strr = append(strr, res)
				playerinfo := &msg.ChampshipsPlayerInfo{}
				playerinfo.DwUin = dwUin
				playerinfo.IsGet = 0
				playerinfo.IsPlayer = 1
				playerinfo.Score = 0
				playerinfo.Times = 1
				playerinfo.AIEnum = 0
				playerinfo.CurChampshipsId = G_GameLogicPtr.M_SvrGlobal.CurChampshipsId
				CSPlayerInfo = append(CSPlayerInfo, playerinfo)
			}
			for j := int(playerCnt); j < 30; j++ {
				StartRobotUin = StartRobotUin + 1
				dwUin := StartRobotUin
				enum := rand.Intn(4) + 1
				res := strconv.Itoa(int(dwUin)) + "_" + "0" + "_" + "0" + "_" + "0" + "_" + "1" + "_" + strconv.Itoa(int(G_GameLogicPtr.M_SvrGlobal.CurChampshipsId)) + "_" + strconv.Itoa(enum)
				strr = append(strr, res)
				playerinfo := &msg.ChampshipsPlayerInfo{}
				playerinfo.DwUin = int32(dwUin)
				playerinfo.IsGet = 0
				playerinfo.IsPlayer = 0
				playerinfo.Score = 0
				playerinfo.Times = 1
				playerinfo.AIEnum = int32(enum)
				playerinfo.CurChampshipsId = G_GameLogicPtr.M_SvrGlobal.CurChampshipsId
				CSPlayerInfo = append(CSPlayerInfo, playerinfo)
			}
			temp.GroupRankData = strings.Join(strr, ";")
			insertId, _ := db.FormatAllMemInsertDb(&temp, "t_championships_data")

			p.MChampshipPlayerMap[int32(insertId)] = CSPlayerInfo

			for j := 0; j < int(playerCnt); j++ {
				dwUin := sqlStrucks[i*int(playerCnt)+j].DwUin
				player, ok := G_GameLogicPtr.M_Players[dwUin]
				if ok {
					player.GetIFGameData("PlayerBaseData").(*PlayerBaseData).SetChampshipID(int32(insertId), true)
				} else {
					player = G_GameLogicPtr.FindOfflinePlayer(dwUin)
					if player != nil {
						player.GetIFGameData("PlayerBaseData").(*PlayerBaseData).SetChampshipID(int32(insertId), false)
					} else {
						sqlStrucks[i*int(playerCnt)+j].LastChampGroupID = sqlStrucks[i*int(playerCnt)+j].ChampshipsGroupID
						sqlStrucks[i*int(playerCnt)+j].ChampshipsGroupID = int32(insertId)
						db.FormatAllMemUpdateDb(&sqlStrucks[i*int(playerCnt)+j], "t_player_baseinfo", "dwUin")
					}
				}
			}
		} else {
			remain := len(sqlStrucks) - (groups-1)*int(playerCnt)
			cnt := 0
			strr := []string{}
			temp := db.SqlChampshipsStruct{}
			temp.CurChampshipsId = G_GameLogicPtr.M_SvrGlobal.CurChampshipsId

			CSPlayerInfo := []*msg.ChampshipsPlayerInfo{}

			for j := 0; j < remain; j++ {
				dwUin := sqlStrucks[i*int(playerCnt)+j].DwUin
				res := strconv.Itoa(int(dwUin)) + "_" + "1" + "_" + "0" + "_" + "0" + "_" + "1" + "_" + strconv.Itoa(int(G_GameLogicPtr.M_SvrGlobal.CurChampshipsId)) + "_0"
				strr = append(strr, res)
				cnt = cnt + 1
				playerinfo := &msg.ChampshipsPlayerInfo{}
				playerinfo.DwUin = dwUin
				playerinfo.IsGet = 0
				playerinfo.IsPlayer = 1
				playerinfo.Score = 0
				playerinfo.Times = 1
				playerinfo.AIEnum = 0
				playerinfo.CurChampshipsId = G_GameLogicPtr.M_SvrGlobal.CurChampshipsId
				CSPlayerInfo = append(CSPlayerInfo, playerinfo)
			}
			for j := cnt; j < 30; j++ {
				StartRobotUin = StartRobotUin + 1
				dwUin := StartRobotUin
				enum := rand.Intn(4) + 1
				res := strconv.Itoa(int(dwUin)) + "_" + "0" + "_" + "0" + "_" + "0" + "_" + "1" + "_" + strconv.Itoa(int(G_GameLogicPtr.M_SvrGlobal.CurChampshipsId)) + "_" + strconv.Itoa(enum)
				strr = append(strr, res)
				playerinfo := &msg.ChampshipsPlayerInfo{}
				playerinfo.DwUin = int32(dwUin)
				playerinfo.IsGet = 0
				playerinfo.IsPlayer = 0
				playerinfo.Score = 0
				playerinfo.Times = 1
				playerinfo.AIEnum = int32(enum)
				playerinfo.CurChampshipsId = G_GameLogicPtr.M_SvrGlobal.CurChampshipsId
				CSPlayerInfo = append(CSPlayerInfo, playerinfo)
			}
			temp.GroupRankData = strings.Join(strr, ";")
			insertId, _ := db.FormatAllMemInsertDb(&temp, "t_championships_data")
			p.MChampshipPlayerMap[int32(insertId)] = CSPlayerInfo
			for j := 0; j < remain; j++ {
				dwUin := sqlStrucks[i*int(playerCnt)+j].DwUin
				player, ok := G_GameLogicPtr.M_Players[dwUin]
				if ok {
					player.GetIFGameData("PlayerBaseData").(*PlayerBaseData).SetChampshipID(int32(insertId), true)
				} else {
					player = G_GameLogicPtr.FindOfflinePlayer(dwUin)
					if player != nil {
						player.GetIFGameData("PlayerBaseData").(*PlayerBaseData).SetChampshipID(int32(insertId), false)
					} else {

						sqlStrucks[i*int(playerCnt)+j].LastChampGroupID = sqlStrucks[i*int(playerCnt)+j].ChampshipsGroupID
						sqlStrucks[i*int(playerCnt)+j].ChampshipsGroupID = int32(insertId)
						db.FormatAllMemUpdateDb(&sqlStrucks[i*int(playerCnt)+j], "t_player_baseinfo", "dwUin")
					}
				}
			}
		}
	}
	p.IsLoadDB = true

	p.AIScoreGrowth1h()
	db.FormatAllMemUpdateDb(&G_GameLogicPtr.M_SvrGlobal, "t_server_global_data", "Id")

}

func (p *ChampshipsManager) OpenChampShipTimes(args []interface{}) {
	p.MStatus = 2
	notify := &msg.NotifyChampshipTimesOpen{}
	notify.CurChampshipsId = G_GameLogicPtr.M_SvrGlobal.CurChampshipsId
	data, _ := proto.Marshal(notify)
	G_GameLogicPtr.broadcastInfoAllPlayer("NotifyChampshipTimesOpen", data)
}

func (p *ChampshipsManager) CloseChampShipTimes(args []interface{}) {
	p.MStatus = 1
	notify := &msg.NotifyChampshipTimesClose{}
	notify.CurChampshipsId = G_GameLogicPtr.M_SvrGlobal.CurChampshipsId
	data, _ := proto.Marshal(notify)
	G_GameLogicPtr.broadcastInfoAllPlayer("NotifyChampshipTimesClose", data)
}

func (p *ChampshipsManager) Notify_Clock_Tick_Sec(args []interface{}) {
	timeStamp := args[0].(int64)
	t := time.Unix(timeStamp, 0).Local()
	zero := timeStamp - (int64)(t.Hour()*3600+t.Minute()*60+t.Second())
	OpenTime := zero + MergeConst.G_Champion_Start_Offset
	OpenTimesTime := zero + MergeConst.G_Champion_Start_Effect_Time
	CloseTimesTime := zero + MergeConst.G_Champion_Start_Effect_Time + MergeConst.G_Champion_Start_Effect_Durtion
	DeleteLastTimesTime := zero + MergeConst.G_Champion_settlement_Duration
	if G_GameLogicPtr.M_SvrGlobal.StartChampshipsSvrTime < int32(OpenTime) { //今日没有开启
		if timeStamp >= OpenTime { //开启
			GoUtil.CallEvent(MergeConst.Notify_Champion_Renew, []interface{}{int32(OpenTime)})
		} else {
			//开启时间未到
			if p.MStatus == 1 {
				GoUtil.CallEvent(MergeConst.Notify_EndChampShip, []interface{}{int32(OpenTime)})
			}

		}
	} else {
		if p.MStatus == 0 {
			p.MStatus = 1
		}

		if !p.IsLoadDB {
			p.LoadDbDataByGroupId(G_GameLogicPtr.M_SvrGlobal.CurChampshipsId)
			if G_GameLogicPtr.M_SvrGlobal.LastChampshipsId > 0 {
				p.LoadDbDataByGroupId(G_GameLogicPtr.M_SvrGlobal.LastChampshipsId)
			}
			p.IsLoadDB = true
		}
	}

	if p.MStatus == 1 {
		if timeStamp >= OpenTimesTime && timeStamp <= CloseTimesTime {
			GoUtil.CallEvent(MergeConst.Notify_OpenChampShipTimes, []interface{}{int32(OpenTime)})
		}

	}
	if p.MStatus == 2 {
		if timeStamp > CloseTimesTime {
			GoUtil.CallEvent(MergeConst.Notify_CloseChampShipTimes, []interface{}{int32(OpenTime)})
		}
	}
	if p.IsSettle == 0 {
		if timeStamp <= DeleteLastTimesTime {
			p.IsSettle = 1
		} else {
			if G_GameLogicPtr.M_SvrGlobal.LastChampshipsId > 0 {
				p.DeleteOutLineChampship(G_GameLogicPtr.M_SvrGlobal.LastChampshipsId)
				G_GameLogicPtr.M_SvrGlobal.LastChampshipsId = 0
				db.FormatAllMemUpdateDb(&G_GameLogicPtr.M_SvrGlobal, "t_server_global_data", "Id")
			}
		}
	}
	if p.IsSettle == 1 {
		if timeStamp > DeleteLastTimesTime {
			notify := &msg.NotifyChampshipSettleClose{}
			notify.LastChampshipsId = G_GameLogicPtr.M_SvrGlobal.LastChampshipsId
			data, _ := proto.Marshal(notify)
			G_GameLogicPtr.broadcastInfoAllPlayer("NotifyChampshipSettleClose", data)
			p.IsSettle = 0
			if G_GameLogicPtr.M_SvrGlobal.LastChampshipsId > 0 {
				p.DeleteOutLineChampship(G_GameLogicPtr.M_SvrGlobal.LastChampshipsId)
				G_GameLogicPtr.M_SvrGlobal.LastChampshipsId = 0
				db.FormatAllMemUpdateDb(&G_GameLogicPtr.M_SvrGlobal, "t_server_global_data", "Id")
			}

		}
	}
}

func (p *ChampshipsManager) EndChampShip(args []interface{}) {
	p.MStatus = 0
	G_GameLogicPtr.M_SvrGlobal.LastChampshipsId = G_GameLogicPtr.M_SvrGlobal.CurChampshipsId
	db.FormatAllMemUpdateDb(&G_GameLogicPtr.M_SvrGlobal, "t_server_global_data", "Id")

	notify := &msg.NotifyChampshipSettleOpen{}
	notify.LastChampshipsId = G_GameLogicPtr.M_SvrGlobal.LastChampshipsId
	data, _ := proto.Marshal(notify)
	G_GameLogicPtr.broadcastInfoAllPlayer("NotifyChampshipSettleOpen", data)

	notify1 := &msg.NotifyChampshipClose{}
	notify1.CurChampshipsId = G_GameLogicPtr.M_SvrGlobal.CurChampshipsId
	data1, _ := proto.Marshal(notify1)
	G_GameLogicPtr.broadcastInfoAllPlayer("NotifyChampshipClose", data1)

	p.NotifyRenewChampshipData()
}

func (p *ChampshipsManager) NotifyRenewChampshipData() {
	for i := 0; i < len(p.MUpdateNotifyList); i++ {
		groupid := p.MUpdateNotifyList[i]
		playerlist, ok := p.MChampshipPlayerMap[groupid]
		if ok {
			for j := 0; j < len(playerlist); j++ {
				if playerlist[j].IsPlayer == 1 {
					dwUin := playerlist[j].DwUin
					player, ok1 := G_GameLogicPtr.M_Players[dwUin]
					if ok1 {
						agent := player.GetAgentByPlayer()
						notify := &msg.NotifyUpdateChampshipRank{}
						notify.ChampshipsGroupID = groupid
						notify.GroupRankDataList = playerlist
						data, _ := proto.Marshal(notify)
						G_getGameLogic().PackResInfo(agent, "NotifyUpdateChampshipRank", data)
					} else {

					}
				}
			}
		}
	}
	p.MUpdateNotifyList = p.MUpdateNotifyList[0:0]
}

func (p *ChampshipsManager) ReqChampshipData(player *Player, buf []byte) {
	req := &msg.ReqChampshipData{}
	proto.Unmarshal(buf, req)
	res := &msg.ResChampshipData{}
	_, ok := p.MChampshipPlayerMap[req.ChampshipsGroupID]
	if ok {
		res.GroupRankDataList = p.MChampshipPlayerMap[req.ChampshipsGroupID]
	}
	res.ChampshipsGroupID = req.ChampshipsGroupID
	res.Status = p.MStatus
	res.IsSettle = p.IsSettle
	res.EndTime = G_GameLogicPtr.M_SvrGlobal.StartChampshipsSvrTime + MergeConst.G_Champion_Duration
	res.EndSettleTime = G_GameLogicPtr.M_SvrGlobal.StartChampshipsSvrTime - MergeConst.G_Champion_Start_Offset + MergeConst.G_Champion_Start_Effect_Time + MergeConst.G_Champion_Start_Effect_Durtion
	agent := player.GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResChampshipData", data)
}

func (p *ChampshipsManager) InitManager() {
	GoUtil.RegisterEvent(MergeConst.Notify_Champion_Renew, p.OpenNewChampShip, p)
	GoUtil.RegisterEvent(MergeConst.Notify_OpenChampShipTimes, p.OpenChampShipTimes, p)
	GoUtil.RegisterEvent(MergeConst.Notify_CloseChampShipTimes, p.CloseChampShipTimes, p)
	GoUtil.RegisterEvent(MergeConst.Notify_EndChampShip, p.EndChampShip, p)
	GoUtil.RegisterEvent(MergeConst.Notify_Clock_Tick_Sec, p.Notify_Clock_Tick_Sec, p)
	p.MChampshipMap = make(map[int32]*db.SqlChampshipsStruct)
	p.MChampshipPlayerMap = make(map[int32][]*msg.ChampshipsPlayerInfo)
	p.MStatus = 0
	p.IsSettle = 0
	p.IsLoadDB = false
	p.MUpdateNotifyList = []int32{}
	p.McronSave = cron.New()
	p.McronSaveID, _ = p.McronSave.AddFunc("@every 70s", func() {
		p.NotifyRenewChampshipData()
	})
	p.RobotCronID, _ = p.McronSave.AddFunc("@every 1h", func() {
		p.AIScoreGrowth1h()
	})

	p.RobotCronID10s, _ = p.McronSave.AddFunc("@every 15m", func() {
		if p.MStatus == 2 {
			p.RobotIntervalAddScore15m()
		}
	})
	p.McronSave.Start()
}

func (p *ChampshipsManager) RobotIntervalAddScore() {
	seed := time.Now().Unix()
	rand.Seed(seed)
	needToUpdateDb := []int32{}
	for k, v := range p.MChampshipPlayerMap {
		ishaveRobot := false
		for i := 0; i < len(v); i++ {
			if v[i].IsPlayer == 0 {
				ishaveRobot = true
				addScore := 3
				ran := rand.Intn(100) + 1
				if ran <= 25 {
					addScore = addScore + 1
				} else {
					if ran <= 50 {
						addScore = addScore + 2
					}
				}
				v[i].Score = v[i].Score + int32(addScore)
			}
		}
		if ishaveRobot {
			sort.Slice(v, func(i, j int) bool { return v[i].Score > v[j].Score })
			isAdd := false
			for i := 0; i < len(p.MUpdateNotifyList); i++ {
				if p.MUpdateNotifyList[i] == k {
					isAdd = true
					break
				}
			}
			if !isAdd {
				p.MUpdateNotifyList = append(p.MUpdateNotifyList, k)
			}
			needToUpdateDb = append(needToUpdateDb, k)

		}

	}
	for i := 0; i < len(needToUpdateDb); i++ {
		p.SaveDbDataByGroupId(needToUpdateDb[i])
	}
}

func (p *ChampshipsManager) GetMinGroupId() int32 {
	var Min int32 = 0
	for k, _ := range p.MChampshipPlayerMap {
		if Min == 0 {
			Min = k
			continue
		}
		if k < Min {
			Min = k
		}
	}
	return Min
}

func (p *ChampshipsManager) AIScoreGrowth1h() {
	seed := time.Now().Unix()
	rand.Seed(seed)
	needToUpdateDb := []int32{}
	// MinGroupId := p.GetMinGroupId()
	for k, v := range p.MChampshipPlayerMap {
		ishaveRobot := false
		groupId := 0 //k - MinGroupId + 1
		for i := 0; i < len(v); i++ {
			if v[i].IsPlayer == 0 {
				ishaveRobot = true
				addScore := 0
				if v[i].AIEnum == 1 {
					var num1 float64 = 0.5
					var num2 float64 = 5.5
					groupId = rand.Intn(7) + 1
					addScore = addScore + int(math.Floor(float64(groupId-1)*num1*num2))
				}
				if v[i].AIEnum == 2 {
					addScore = 16

					ran := rand.Intn(100) + 1
					if ran <= 25 {
						addScore = addScore + 6
					} else {
						if ran <= 50 {
							addScore = addScore + 10
						}
					}
				}
				if v[i].AIEnum == 3 {
					addScore = 16

					ran := rand.Intn(100) + 1
					if ran <= 25 {
						addScore = addScore + 10
					} else {
						if ran <= 75 {
							addScore = addScore + 6
						}
					}
					var num1 float64 = 0.5
					var num2 float64 = 5.5
					groupId = rand.Intn(7) + 1
					addScore = addScore + int(math.Floor(float64(groupId-1)*num1*num2))
				}
				if v[i].AIEnum == 4 {
					var num1 float64 = 0.5
					var num2 float64 = 5.5
					groupId = rand.Intn(7) + 1
					addScore = addScore + int(math.Floor(float64(groupId-1)*num1*num2))
					score := rand.Intn(23)
					addScore = addScore + score
				}
				v[i].Score = v[i].Score + int32(addScore)
			}
		}
		if ishaveRobot {
			sort.Slice(v, func(i, j int) bool { return v[i].Score > v[j].Score })
			isAdd := false
			for i := 0; i < len(p.MUpdateNotifyList); i++ {
				if p.MUpdateNotifyList[i] == k {
					isAdd = true
					break
				}
			}
			if !isAdd {
				p.MUpdateNotifyList = append(p.MUpdateNotifyList, k)
			}
			needToUpdateDb = append(needToUpdateDb, k)

		}

	}
	for i := 0; i < len(needToUpdateDb); i++ {
		p.SaveDbDataByGroupId(needToUpdateDb[i])
	}
}

func (p *ChampshipsManager) RobotIntervalAddScore15m() {
	seed := time.Now().Unix()
	rand.Seed(seed)
	needToUpdateDb := []int32{}
	for k, v := range p.MChampshipPlayerMap {
		ishaveRobot := false
		for i := 0; i < len(v); i++ {
			if v[i].IsPlayer == 0 {

				addScore := 0
				if v[i].AIEnum == 1 {

					ran := rand.Intn(100) + 1
					if ran <= 25 {
						addScore = addScore + 10
					} else {
						if ran <= 75 {
							addScore = addScore + 6
						}
					}
					ran = rand.Intn(100) + 1
					if ran <= 25 {
						addScore = addScore + 5
					} else {
						if ran <= 50 {
							addScore = addScore + 10
						}
					}
					if addScore > 0 {
						ishaveRobot = true
						v[i].Score = v[i].Score + int32(addScore)
					}

				}

			}
		}
		if ishaveRobot {
			sort.Slice(v, func(i, j int) bool { return v[i].Score > v[j].Score })
			isAdd := false
			for i := 0; i < len(p.MUpdateNotifyList); i++ {
				if p.MUpdateNotifyList[i] == k {
					isAdd = true
					break
				}
			}
			if !isAdd {
				p.MUpdateNotifyList = append(p.MUpdateNotifyList, k)
			}
			needToUpdateDb = append(needToUpdateDb, k)

		}

	}
	for i := 0; i < len(needToUpdateDb); i++ {
		p.SaveDbDataByGroupId(needToUpdateDb[i])
	}
}
func (p *ChampshipsManager) SaveDbDataByGroupId(GroupId int32) {
	_, ok := p.MChampshipPlayerMap[GroupId]
	if ok {
		List := p.MChampshipPlayerMap[GroupId]
		strr := []string{}
		for i := 0; i < len(List); i++ {
			Item := List[i]
			unit := strconv.Itoa(int(Item.DwUin)) + "_" + strconv.Itoa(int(Item.IsPlayer)) + "_" + strconv.Itoa(int(Item.Score)) + "_" + strconv.Itoa(int(Item.IsGet)) + "_" + strconv.Itoa(int(Item.Times)) + "_" + strconv.Itoa(int(Item.CurChampshipsId)) + "_" + strconv.Itoa(int(Item.AIEnum))
			strr = append(strr, unit)
		}
		data := strings.Join(strr, ";")
		sqlStruct := &db.SqlChampionshipsStruct{}
		sqlStruct.ChampshipsGroupID = GroupId
		sqlStruct.GroupRankData = data
		sqlStruct.CurChampshipsId = List[0].CurChampshipsId
		db.FormatAllMemUpdateDb(sqlStruct, "t_championships_data", "ChampshipsGroupID")
	}
}

func (p *ChampshipsManager) LoadDbDataByGroupId(ChampshipsId int32) {

	sqlStr := "SELECT * FROM t_championships_data WHERE CurChampshipsId = ?"

	sqlStruck := []db.SqlChampionshipsStruct{}

	if err := db.SqlDb.Select(&sqlStruck, sqlStr, ChampshipsId); err != nil {
		fmt.Printf("get data failed, err:%v\n", err)

	} else {
		for m := 0; m < len(sqlStruck); m++ {
			units := strings.Split(sqlStruck[m].GroupRankData, ";")
			list := []*msg.ChampshipsPlayerInfo{}
			for i := 0; i < len(units); i++ {
				item := units[i]
				strr := strings.Split(item, "_")
				temp := &msg.ChampshipsPlayerInfo{}
				dwuin, _ := strconv.Atoi(strr[0])
				temp.DwUin = int32(dwuin)
				IsPlayer, _ := strconv.Atoi(strr[1])
				temp.IsPlayer = int32(IsPlayer)
				Score, _ := strconv.Atoi(strr[2])
				temp.Score = int32(Score)
				IsGet, _ := strconv.Atoi(strr[3])
				temp.IsGet = int32(IsGet)
				Times, _ := strconv.Atoi(strr[4])
				temp.Times = int32(Times)
				CS, _ := strconv.Atoi(strr[5])
				temp.CurChampshipsId = int32(CS)
				AI, _ := strconv.Atoi(strr[6])
				temp.AIEnum = int32(AI)
				list = append(list, temp)
			}
			p.MChampshipPlayerMap[sqlStruck[m].ChampshipsGroupID] = list
		}
	}

}

func (p *ChampshipsManager) ReqChampshipAddScore(player *Player, buf []byte) {
	req := &msg.ReqChampshipAddScore{}
	proto.Unmarshal(buf, req)
	res := &msg.ResChampshipAddScore{}

	if p.MStatus == 0 {
		res.ResultCode = MergeConst.Protocol_Champship_End
	} else {
		_, ok := p.MChampshipPlayerMap[req.GroupId]
		if ok {
			List := p.MChampshipPlayerMap[req.GroupId]
			isHave := false
			for i := 0; i < len(List); i++ {
				if List[i].DwUin == player.M_DwUin {
					List[i].Score = List[i].Score + req.AddScore
					res.ResultCode = 0
					isHave = true
					break
				}
			}
			sort.Slice(List, func(i, j int) bool { return List[i].Score > List[j].Score })
			if !isHave {
				res.ResultCode = MergeConst.Protocol_Champship_No_Join
			} else {
				res.GroupRankDataList = List
				isAdd := false
				for i := 0; i < len(p.MUpdateNotifyList); i++ {
					if p.MUpdateNotifyList[i] == req.GroupId {
						isAdd = true
						break
					}
				}
				if !isAdd {
					p.MUpdateNotifyList = append(p.MUpdateNotifyList, req.GroupId)
				}

				p.SaveDbDataByGroupId(req.GroupId)
			}
		} else {
			res.ResultCode = MergeConst.Protocol_Champship_No_Exsit
		}
	}

	res.GroupId = req.GroupId
	agent := player.GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResChampshipAddScore", data)
}

func (p *ChampshipsManager) ReqChampshipAddTime(player *Player, buf []byte) {
	req := &msg.ReqChampshipAddTime{}
	proto.Unmarshal(buf, req)
	res := &msg.ResChampshipAddTime{}
	if p.MStatus == 0 {
		res.ResultCode = MergeConst.Protocol_Champship_End
	} else {
		_, ok := p.MChampshipPlayerMap[req.GroupId]
		if ok {
			List := p.MChampshipPlayerMap[req.GroupId]
			isHave := false
			for i := 0; i < len(List); i++ {
				if List[i].DwUin == player.M_DwUin {
					List[i].Times = List[i].Times + req.AddTimes
					res.ResultCode = 0
					isHave = true
					break
				}
			}
			sort.Slice(List, func(i, j int) bool { return List[i].Score > List[j].Score })
			if !isHave {
				res.ResultCode = MergeConst.Protocol_Champship_No_Join
			} else {
				res.GroupRankDataList = List
				p.SaveDbDataByGroupId(req.GroupId)
			}
		} else {
			res.ResultCode = MergeConst.Protocol_Champship_No_Exsit
		}
	}
	res.GroupId = req.GroupId

	agent := player.GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResChampshipAddTime", data)
}

func (p *ChampshipsManager) ReqChampshipReward(player *Player, buf []byte) {
	req := &msg.ReqChampshipReward{}
	proto.Unmarshal(buf, req)
	res := &msg.ResChampshipReward{}

	res.ResultCode = 0
	List, ok := p.MChampshipPlayerMap[req.GroupId]
	if ok {
		sort.Slice(List, func(i, j int) bool { return List[i].Score > List[j].Score })
		for i := 0; i < len(List); i++ {
			if List[i].DwUin == player.M_DwUin {
				if List[i].IsGet == 0 {
					List[i].IsGet = 1
					p.SaveDbDataByGroupId(req.GroupId)
				} else {
					res.ResultCode = MergeConst.Protocol_Champship_Have_GetWarded
				}

				break
			}
		}
	} else {
		res.ResultCode = MergeConst.Protocol_Champship_No_Exsit
	}

	agent := player.GetAgentByPlayer()
	data, _ := proto.Marshal(res)
	G_getGameLogic().PackResInfo(agent, "ResChampshipReward", data)
}
